#!/bin/bash

R="\\033[1;31m"
V="\\033[1;32m"
J="\\033[1;33m"
N="\\033[0;39m"

if [ $USER != "root" ]; then
	echo -n "$R"
	echo -n "Doit être lancé en tant que root."
	echo "$N"
	exit 1
fi

CUR_DIR=`pwd`

LOG_FILE=$CUR_DIR/pma-install-`date +"%Y%m%d%H%M%S"`.log

touch $LOG_FILE

# Installation de phpMyAdmin
echo -n "Installation de phpMyAdmin : "

apt-get install -y php5-mcrypt &>> $LOG_FILE

# Création du dossier principal si besoin.
if [ ! -d "/opt/php-factory" ]; then
        mkdir /opt/php-factory
fi

cd /opt/php-factory

tar -xzf $CUR_DIR/repository/phpMyAdmin-3.3.1-all-languages.tar.gz &>> $LOG_FILE

if [ "$?" = 0 ]; then
	echo -e "$V OK $N"
else
	echo -e "$R KO $N"
	exit 1
fi 

# Création du dossier de config si besoin.
if [ ! -d "/etc/php-factory" ]; then
        mkdir /etc/php-factory
fi

if [ ! -d "/etc/php-factory/phpMyAdmin-3.3.1-all-languages" ]; then
        mkdir /etc/php-factory/phpMyAdmin-3.3.1-all-languages
fi

cp $CUR_DIR/conf/pma-vhost.conf-dist /etc/php-factory/phpMyAdmin-3.3.1-all-languages/apache2.conf

ln -s /etc/php-factory/phpMyAdmin-3.3.1-all-languages/apache2.conf /etc/apache2/sites-enabled/phpmyadmin.conf

mv /opt/php-factory/phpMyAdmin-3.3.1-all-languages/config.sample.inc.php /etc/php-factory/phpMyAdmin-3.3.1-all-languages/config.php

ln -s /etc/php-factory/phpMyAdmin-3.3.1-all-languages/config.php /opt/php-factory/phpMyAdmin-3.3.1-all-languages/config.inc.php

# Utilisation de la somme MD5 du FQDN comme paramètre blowfish_secret
sed -i "s/\$cfg\['blowfish_secret'\] = '';/\$cfg\['blowfish_secret'\] = '`hostname -f | md5sum | grep -o '[a-f0-9]*'`';/" /opt/php-factory/phpMyAdmin-3.3.1-all-languages/config.inc.php

sudo chown --recursive www-data:www-data /opt/php-factory/phpMyAdmin-3.3.1-all-languages

# todo: ajout du produit aux produits du backoffice
# todo: ajouter la configuration des tables liées

service apache2 reload
